package com.test.user.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class App2Backend {
	Map<String, String> jwtToToken = new HashMap<String, String>();

	@RequestMapping(value = "/hswapp2-backend/authorize-callback", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public Object authorizeCallback(HttpServletRequest request, HttpServletResponse resp) throws IOException {
		String code = request.getParameter("code");
		String appSite = request.getParameter("appsite");
		System.out.println("/hswapp2-backend/authorize-callback?code=" + code + "&appsite=" + appSite);
		JSONObject params = new JSONObject();
		params.put("client_id", "hsw-app2");
		params.put("client_secret", "hsw-app2-secret");
		params.put("grant_type", "authorization_code");
		params.put("code", code);
		// 创建执行请求的HttpClient对象
		HttpClient client = HttpClients.createDefault();
		String url = "http://192.168.0.105:8089/oauth/token";
		// 创建post请求对象
		HttpPost post = new HttpPost(url);
		// 创建StringEntity对象，并将参数封装到该对象中，注意必须设置编码格式，否则参数会乱码
		System.out.println(params.toString());
		StringEntity entity = new StringEntity(params.toString(), "UTF-8");
		// 将参数放入请求对象中
		post.setEntity(entity);
		// 发送请求
		HttpResponse response = client.execute(post);
		if (response.getStatusLine().getStatusCode() == 200) {
			// 获取返回的token
			System.out.println("获取返回的token");
			HttpEntity result = response.getEntity();
			String messageString = EntityUtils.toString(result, "UTF-8");
			System.out.println(messageString);
			JSONObject message = (JSONObject) JSONObject.parse(messageString);
			// 生成JWT, Set Cookie, return App
			String randomJWT = getRandomString(20);
			JSONObject info = message.getJSONObject("info");
			String token = message.getString("access_token");
			System.out.println("put jwtToUserinfo: " + randomJWT + ", " + info.getString("username"));
			jwtToToken.put(randomJWT, token);
			return new ModelAndView("redirect:" + appSite + "?jwt=" + randomJWT);
		}
		return null;
	}

	@RequestMapping(value = "/hswapp2-backend/checkjwt", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public void checkJWT(HttpServletRequest request, HttpServletResponse resp) throws IOException {
		String jwt = request.getParameter("jwt");
		String callback = request.getParameter("jsonpCallback");
		System.out.println(jwt);
		System.out.println(callback);
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json; charset=utf-8");
		JSONObject o = new JSONObject();
		PrintWriter writer = resp.getWriter();
		if (jwtToToken.get(jwt) != null) {
			// Ask Auth for Userinfo
			HttpClient client = HttpClients.createDefault();
			String url = "http://192.168.0.105:8089/oauth/userinfo";
			HttpPost post = new HttpPost(url);
			JSONObject params = new JSONObject();
			String token = jwtToToken.get(jwt);
			params.put("access_token", token);
			StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
			post.setEntity(stringEntity);
			// 发送请求
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				JSONObject resultJsonObject = null;
				StringBuilder entityStringBuilder = new StringBuilder();
				String line = null;
				BufferedReader b = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"),
						8 * 1024);
				line = b.readLine();
				resultJsonObject = JSONObject.parseObject(line);
				String userName = resultJsonObject.getString("username");
				if (userName == null) {
					o.put("status", "fail");
				} else {
					o.put("status", "success");
					o.put("username", userName);
				}
				writer.write(callback + "(" + JSONObject.toJSONString(o) + ")");
			}
		} else {
			o.put("message", "invalid JWT");
			writer.write(callback + "(" + JSONObject.toJSONString(o) + ")");
		}
	}

	@RequestMapping(value = "/hswapp2-backend/logout", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public void logout(HttpServletRequest request, HttpServletResponse resp) throws IOException {
		HttpClient client = HttpClients.createDefault();
		String callback = request.getParameter("jsonpCallback");
		String url = "http://192.168.0.105:8089/oauth/logout";
		String jwt = request.getParameter("jwt");
		// 创建post请求对象
		HttpPost post = new HttpPost(url);
		JSONObject params = new JSONObject();
		String token = jwtToToken.get(request.getParameter("jwt"));
		params.put("access_token", token);
		StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
		post.setEntity(stringEntity);
		// 发送请求
		HttpResponse response = client.execute(post);
		if (response.getStatusLine().getStatusCode() == 200) {
			jwtToToken.remove(jwt);
			Cookie authSiteCookie = new Cookie("hswapp2_jwt", "");
			// 设置cookie的持久化时间，60s
			authSiteCookie.setMaxAge(0);
			// 设置为当前项目下都携带这个cookie
			authSiteCookie.setPath("/");
			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/json; charset=utf-8");
			PrintWriter writer = resp.getWriter();
			resp.addCookie(authSiteCookie);
			JSONObject o = new JSONObject();
			o.put("status", "success");
			writer.write(callback + "(" + JSONObject.toJSONString(o) + ")");
		}
	}

	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer valSb = new StringBuffer();
		String charStr = "0123456789abcdefghijklmnopqrstuvwxyz";
		int charLength = charStr.length();

		for (int i = 0; i < length; i++) {
			int index = random.nextInt(charLength);
			valSb.append(charStr.charAt(index));
		}
		return valSb.toString();
	}
}
